package org.cupk2.service.controller;

import com.cupk2.lucene.Cupk2LuceneFace;
import com.cupk2.lucene.inter.Cupk2LuceneIndexInter;
import com.cupk2.lucene.query.DocumentQuery;
import com.cupk2.lucene.query.rule.DocumentRuleByTerm;
import com.cupk2.lucene.result.DocumentResult;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.cupk2.base.domain.CupkUserContextLoader;
import org.cupk2.service.lucene.doc.enums.DocumentTitleEnum;
import org.cupk2.service.lucene.doc.enums.IndexModelEnum;
import org.cupk2.zhzm.dto.web.WebKnowDto;
import org.cupk2.zhzm.domain.ZhzmKnow;
import org.cupk2.zhzm.service.ZhzmKnowServiceInter;
import org.cupk2.tools.bean.CupkBeanUtils;
import org.cupk2.tools.db.ResultDataHandle;
import org.cupk2.tools.web.CupkResponseCode;
import org.cupk2.tools.web.CupkResponseResult;
import org.cupk2.tools.web.dto.IdDto;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 知识
 *
 */
@RestController
@RequestMapping("/api/wknow")
public class WebKnowController {
    @Autowired
    private ZhzmKnowServiceInter zhzmKnowServiceImpl;

    /**
     * 加载知识内容
     *
     * @param id
     * @return
     */
    @PreAuthorize("@cupkAction.has('wknow.view')")
    @PostMapping("/view")
    public CupkResponseResult view(@RequestBody IdDto id) {
        ZhzmKnow know = zhzmKnowServiceImpl.getZhzmKnowById(id.getId());
        if (know == null) {
            Cupk2LuceneIndexInter indexService = Cupk2LuceneFace.getIndexService();
            indexService.deleteIndex(List.of(id.getId()));
            return CupkResponseResult.getInstance(CupkResponseCode.ERROR, "知识不存在：" + id.getId(), null);
        }
        String text = zhzmKnowServiceImpl.getKnowHtml(know);
        WebKnowDto dto = new WebKnowDto();
        CupkBeanUtils.copyProperties(know, dto);
        dto.setText(text);
        dto.setTags(zhzmKnowServiceImpl.getKnowTagDtos(know));
        return CupkResponseResult.getInstance(CupkResponseCode.SUCESS, dto);
    }


    /**
     * 加载知识内容(用于编辑知识)
     *
     * @param id
     * @return
     */
    @PreAuthorize("@cupkAction.has('wknow.view')")
    @PostMapping("/eview")
    public CupkResponseResult viewByEdit(@RequestBody IdDto id) {
        ZhzmKnow know = zhzmKnowServiceImpl.getZhzmKnowById(id.getId());
        if (know == null) {
            Cupk2LuceneIndexInter indexService = Cupk2LuceneFace.getIndexService();
            indexService.deleteIndex(List.of(id.getId()));
            return CupkResponseResult.getInstance(CupkResponseCode.ERROR, "知识不存在：" + id.getId(), null);
        }
        String text = zhzmKnowServiceImpl.getKnowText(know);
        WebKnowDto dto = new WebKnowDto();
        CupkBeanUtils.copyProperties(know, dto);
        dto.setText(Jsoup.parse(text).getElementsByTag("body").html());
        dto.setTags(zhzmKnowServiceImpl.getKnowTagDtos(know));
        return CupkResponseResult.getInstance(CupkResponseCode.SUCESS, dto);
    }

    @PreAuthorize("@cupkAction.has('wknow.pop')")
    @PostMapping("/pop")
    public CupkResponseResult loaduserPop(@RequestBody IdDto id) {
        ZhzmKnow know = zhzmKnowServiceImpl.getZhzmKnowById(id.getId());
        List<String> pops = new ArrayList<>();
        if (know.getCuserkey().equals(CupkUserContextLoader.getCurrentUserKey())) {
            pops.add("DELETE");
            pops.add("EDIT");
        }
        return CupkResponseResult.getInstance(CupkResponseCode.SUCESS, pops);
    }

    @PreAuthorize("@cupkAction.has('wknow.del')")
    @DeleteMapping
    public CupkResponseResult delKnow(@RequestBody IdDto id) {
        ZhzmKnow know = zhzmKnowServiceImpl.getZhzmKnowById(id.getId());
        if (!know.getCuserkey().equals(CupkUserContextLoader.getCurrentUserKey())) {
            return CupkResponseResult.getInstance(CupkResponseCode.ERROR, "无操作权限");
        }
        zhzmKnowServiceImpl.delZhzmKnow(id.getId());
        return CupkResponseResult.getInstance(CupkResponseCode.SUCESS);
    }


    /**
     * 创建知识
     *
     * @param webKnowDto
     * @return
     */
    @PreAuthorize("@cupkAction.has('wknow.add')")
    @PostMapping
    public CupkResponseResult addSubmit(@Valid @RequestBody WebKnowDto webKnowDto) {
        ZhzmKnow know = null;
        if (StringUtils.isBlank(webKnowDto.getId())) {
            know = zhzmKnowServiceImpl.creatKnow(webKnowDto);
        } else {
            know = zhzmKnowServiceImpl.editKnow(webKnowDto);
        }
        return CupkResponseResult.getInstance(CupkResponseCode.SUCESS, know);
    }


    /**
     * 获得知识的附件文本
     *
     * @param id
     * @return
     */
    @PreAuthorize("@cupkAction.has('wknow.fileContent')")
    @PostMapping("/fileContent")
    public CupkResponseResult fileContent(@RequestBody IdDto id) {
        ZhzmKnow know = zhzmKnowServiceImpl.getZhzmKnowById(id.getId());
        DocumentResult result = Cupk2LuceneFace.getSearchService().search((new DocumentQuery())
                .setHighlight(false).addRule(new DocumentRuleByTerm(DocumentTitleEnum.model.name(), IndexModelEnum.FILE.name()))
                .addRule(new DocumentRuleByTerm(DocumentTitleEnum.knowId.name(), id.getId())));
        StringBuffer fileContent = new StringBuffer();
        result.runDataHandle(new ResultDataHandle() {
            @Override
            public void handle(Map<String, Object> row) {
                fileContent.append(row.get(DocumentTitleEnum.text.name()));
            }
        });
        String content = "";
        if (fileContent.length() > 30000) {
            content = fileContent.substring(0, 30000 - 1);
        } else {
            content = fileContent.toString();
        }
        return CupkResponseResult.getInstance(CupkResponseCode.SUCESS, "", content);
    }



}
